package org.fs;

import java.io.IOException;
import java.util.Properties;

import org.htmlparser.NodeFilter;
import org.htmlparser.beans.FilterBean;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.tags.InputTag;

public class ConnectionScanner {

	private static final String SKYSCANNER_URL = "http://www.skyscanner.net/flights/";
	String fromString = getProperty("from");
	String toString = getProperty("to");
	
	private ConnectionManager connectionManager;
	private Properties props = null;
	
	public void run(){
		String[] startingAirports = fromString.split(";");
		String[] countries = toString.split(";");
		for (int i = 0; i < startingAirports.length; i++) {
			for (int j = 0; j < countries.length; j++) {
				String from = startingAirports[i];
				String to = countries[j];
				FilterBean fb = new FilterBean();
				fb.setFilters(new NodeFilter[] { new HasAttributeFilter("name", "dfl") });
				String url = SKYSCANNER_URL + from + "/" + to;
				fb.setURL(url);
				connectionManager.setCountry(to);
				for (int k = 0; k < fb.getNodes().size(); k++) {
					InputTag in = (InputTag) fb.getNodes().elementAt(k);
					if(in == null)
						continue;
					String data = in.getAttributeEx("value").getValue();
					connectionManager.saveConnection(from.toUpperCase(), data.toUpperCase());
					System.out.println(data);
				}
			}
		}
	}

	public void setConnectionManager(ConnectionManager connectionManager) {
		this.connectionManager = connectionManager;
	}
	
	public String getProperty(String property){
		if(props == null){
			props = new Properties();
			try {
				props.load(this.getClass().getClassLoader().getResourceAsStream("destinations.properties"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return props.getProperty(property);		
	}
}
